<template>
  <div id="panel">
    <el-card class="queryForm">
      <el-form
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        :label-position="'right'"
      >
        <el-form-item label="设备名称：" prop="equipmentname">
          <el-input
            v-model="queryParams.equipmentname"
            placeholder="请输入设备名称"
          ></el-input>
        </el-form-item>
        <el-form-item style="margin-left: 20px">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"
            >查询</el-button
          >
          <el-button @click="resetQuery" icon="el-icon-refresh-right"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="pageContent">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="handleUpdate"
            :disabled="ids.length !== 1"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete"
            :disabled="ids.length === 0"
            >删除</el-button
          >
        </el-col>
      </el-row>

      <el-table
        :data="tableList.rows"
        stripe
        :height="tableHeight"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="devsn" label="设备编号" />
        <el-table-column prop="equipmentname" label="设备名称" />
        <el-table-column prop="principal" label="负责人" />
        <el-table-column prop="phone" label="负责人电话" />
        <el-table-column prop="address" label="安装地址" />
        <el-table-column prop="longitude" label="经度" />
        <el-table-column prop="latitude" label="纬度" />
        <!-- 溯源类型列：回显汉字 -->
        <el-table-column label="溯源类型" :formatter="tracetype">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.trace_baseinfo_tracetype"
              :value="scope.row.tracetype"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button type="text" @click="edit(scope.row)">修改</el-button>
            <el-button
              type="text"
              @click="delRows(scope.row)"
              style="color: #f56c6c"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination-self"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :pager-count="5"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        layout="slot, total, sizes, prev, pager, next, jumper"
        :total="tableList.total"
      >
        <el-button
          class="refresh-button"
          icon="el-icon-refresh"
          title="刷新"
          @click="getList"
        />
      </el-pagination>
    </el-card>

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="equipmentname">
              <el-input
                v-model="form.equipmentname"
                placeholder="请输入设备名称"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编号" prop="devsn">
              <el-input
                v-model="form.devsn"
                placeholder="请输入设备编号"
                maxlength="30"
                :disabled="form.id !== undefined"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="principal">
              <el-input v-model="form.principal" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入负责人电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="安装地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入安装地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input
                v-model="form.longitude"
                placeholder="请输入经度（例如：117.029334）"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input
                v-model="form.latitude"
                placeholder="请输入纬度（例如：33.427368）"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- 溯源类型下拉选择 -->
            <el-form-item label="溯源类型" prop="tracetype">
              <el-select
                v-model="form.tracetype"
                placeholder="请选择溯源类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.trace_baseinfo_tracetype"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDeviceList,
  addDevice,
  editDevice,
  getDeviceDetail,
  deleteDevice,
} from "@/api/traceability";
export default {
  name: "DeviceManagement",
  dicts: ["trace_baseinfo_tracetype"],
  data() {
    return {
      tableHeight: window.innerHeight - 400,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentname: "", // 设备名称查询字段
      },
      tableList: {
        total: 0,
        rows: [],
      },
      ids: [], // 选中项ID集合（用于批量操作）
      open: false, // 对话框显隐状态
      title: "", // 对话框标题
      // 溯源类型映射：1-河道溯源 2-企业溯源 3-行业溯源 4-面源溯源 5-手持溯源仪
      tracetypeOptions: [],
      form: {
        id: undefined, // 核心：通过id是否存在判断新增/修改
        equipmentname: "",
        devsn: "",
        principal: "",
        phone: "",
        address: "",
        longitude: "",
        latitude: "",
        tracetype: "", // 存储value（1-5）
      },
      // 表单验证规则
      rules: {
        equipmentname: [
          { required: true, message: "设备名称不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "设备名称长度必须介于2-20之间",
            trigger: "blur",
          },
        ],
        devsn: [
          { required: true, message: "设备编号不能为空", trigger: "blur" },
          {
            min: 3,
            max: 30,
            message: "设备编号长度必须介于3-30之间",
            trigger: "blur",
          },
        ],
        principal: [
          { required: true, message: "负责人不能为空", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "负责人电话不能为空", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号格式",
            trigger: "blur",
          },
        ],
        longitude: [
          { required: true, message: "经度不能为空", trigger: "blur" },
          {
            pattern: /^-?((0|1?[0-7]?[0-9]?)|(180))(\.\d{1,6})?$/,
            message: "请输入正确的经度格式（-180至180）",
            trigger: "blur",
          },
        ],
        latitude: [
          { required: true, message: "纬度不能为空", trigger: "blur" },
          {
            pattern: /^-?((0|[1-8]?[0-9]?)|(90))(\.\d{1,6})?$/,
            message: "请输入正确的纬度格式（-90至90）",
            trigger: "blur",
          },
        ],
        tracetype: [
          { required: true, message: "请选择溯源类型", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    // 页面初始化时加载数据
    this.pageInit();
  },
  methods: {
    // 页面初始化
    pageInit() {
      this.getList();
    },

    // 表格选择变化时更新选中的ids
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },

    // 新增设备
    handleAdd() {
      this.reset(); // 重置表单
      this.open = true;
      this.title = "添加设备";
    },

    // 批量修改（表格选择后点击修改按钮）
    handleUpdate() {
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条数据进行修改");
        return;
      }
      this.reset();
      this.open = true;
      this.title = "修改设备";
      // 调用详情接口获取数据
      getDeviceDetail(this.ids[0])
        .then((res) => {
          this.form = { ...res.data }; // 赋值详情数据到表单
        })
        .catch((error) => {
          this.$message.error(
            "获取设备详情失败：" + (error.message || "网络错误")
          );
        });
    },

    // 单行修改（表格操作列点击修改）
    edit(row) {
      this.reset();
      this.open = true;
      this.title = "修改设备";
      // 调用详情接口获取数据
      getDeviceDetail(row.id)
        .then((res) => {
          this.form = { ...res.data };
        })
        .catch((error) => {
          this.$message.error(
            "获取设备详情失败：" + (error.message || "网络错误")
          );
        });
    },

    // 批量删除
    handleDelete() {
      if (this.ids.length === 0) {
        this.$message.warning("请选择至少一条数据进行删除");
        return;
      }
      // 将id数组转为逗号分隔的字符串
      const idsStr = this.ids.join(",");
      this.$confirm(
        `是否确认删除选中的${this.ids.length}条数据？`,
        "删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        }
      )
        .then(() => {
          // 调用删除接口，传入逗号分隔的id字符串
          deleteDevice(idsStr)
            .then(() => {
              this.$message.success("删除成功");
              this.getList(); // 刷新列表
              this.ids = []; // 清空选中状态
            })
            .catch((error) => {
              this.$message.error("删除失败：" + (error.message || "网络错误"));
            });
        })
        .catch(() => {}); // 取消删除不做处理
    },

    // 单行删除（表格操作列点击删除）
    delRows(row) {
      // 单行id转为字符串（保持格式统一）
      const idStr = row.id.toString();
      this.$confirm(`是否确认删除设备"${row.equipmentname}"？`, "删除确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          deleteDevice(idStr)
            .then(() => {
              this.$message.success("删除成功");
              this.getList(); // 刷新列表
            })
            .catch((error) => {
              this.$message.error("删除失败：" + (error.message || "网络错误"));
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },

    // 页码变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    // 查询数据
    handleQuery() {
      this.queryParams.pageNum = 1; // 重置为第一页
      this.getList();
    },

    // 重置查询条件
    resetQuery() {
      this.$refs.queryForm.resetFields(); // 重置表单
      this.getList(); // 重新查询
    },

    // 关闭对话框
    cancel() {
      this.open = false;
      this.reset(); // 重置表单
    },

    // 重置表单数据
    reset() {
      this.form = {
        id: undefined,
        equipmentname: "",
        devsn: "",
        principal: "",
        phone: "",
        address: "",
        longitude: "",
        latitude: "",
        tracetype: "",
      };
      if (this.$refs.form) {
        this.$refs.form.resetFields(); // 重置验证状态
      }
    },

    // 提交表单（新增/修改）
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 根据id是否存在判断新增/修改
          const isEdit = this.form.id !== undefined;
          const request = isEdit ? editDevice(this.form) : addDevice(this.form);

          request
            .then(() => {
              this.open = false; // 关闭对话框
              this.getList(); // 刷新列表
              this.$message.success(isEdit ? "修改成功" : "新增成功");
            })
            .catch((error) => {
              this.$message.error(
                `${isEdit ? "修改" : "新增"}失败：${
                  error.message || "网络错误"
                }`
              );
            });
        }
      });
    },

    // 获取设备列表数据
    getList() {
      getDeviceList(this.queryParams)
        .then((res) => {
          this.tableList.total = res.total || 0;
          this.tableList.rows = res.rows || [];
        })
        .catch((error) => {
          this.$message.error(
            "获取设备列表失败：" + (error.message || "网络错误")
          );
        });
    },

    // 格式化溯源类型：将value（1-5）转换为汉字
    formatTracetype(row) {
      const type = row.tracetype; // 从行数据中获取tracetype（1-5）
      const option = this.tracetypeOptions.find((item) => item.value === type);
      return option ? option.label : "未知类型"; // 找不到时显示"未知类型"
    },
  },
};
</script>

<style lang="scss" scoped>
#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  .el-card {
    margin: 10px;
    border-radius: 4px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  }

  .queryForm .el-card__body {
    padding: 15px 20px !important;
    background-color: #f5f7fa;
  }

  .queryForm .el-form-item {
    margin: 10px 0;
  }

  .queryForm .el-form-item__label {
    padding-right: 10px;
    color: #606266;
    font-weight: 500;
  }

  .searchBtnBox {
    display: inline-block;
    margin-left: 15px;

    .el-button {
      margin-left: 5px;
    }
  }

  .pageContent {
    .mb8 {
      margin-bottom: 8px;
      padding: 10px 0 0 10px;
    }

    .el-table {
      margin-top: 10px;
    }

    .el-table__header-wrapper th {
      background-color: #f5f7fa;
      font-weight: 500;
    }
  }

  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 0;
      color: #409eff;
      font-weight: 500;
    }
  }

  .refresh-button {
    margin-right: 10px;
    color: #409eff;

    .el-icon-refresh {
      font-size: 18px;
      line-height: 28px;
    }
  }

  .dialog-footer {
    text-align: right;

    .el-button {
      margin-left: 10px;
    }
  }
}
</style>
